package team.nmsg.ge.system.controller;

import java.io.Serializable;
import java.sql.Connection;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.bean.SysOper;
import team.nmsg.ge.system.bean.SysRole;
import team.nmsg.ge.system.bean.SysUser;
import team.nmsg.ge.system.init.SysBusiLogAdditThread;
import team.nmsg.ge.system.service.IUserRoleService;
import team.nmsg.ge.system.util.ServerConstants;
import team.nmsg.ge.system.util.ServerParams;

import com.alibaba.fastjson.JSONObject;

@CrossOrigin
@Controller
public class CommonController extends BaseController{
	
	private static Logger log = LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	private IUserRoleService userRoleService;
	
	@RequestMapping(value = { "/login", "/" } , method = RequestMethod.GET )
	public String loginPage(ModelMap modelMap, HttpServletRequest request , HttpSession session) {
		
		RequestContext requestContext = new RequestContext(request);
		
		String isKickOut = request.getParameter(ServerConstants.KEY_KICKOUT);
		if("true".equals(isKickOut) ){
			modelMap.addAttribute("error", requestContext.getMessage("You have bean kick out!"));
		}
		
		Subject subject = SecurityUtils.getSubject();
		if( subject.isAuthenticated() ){
			return "redirect:/home";
		}
		
		
		return "login";
	}
	
	
	
//    @Autowired
//    DataSource dataSource;    
	
	@RequestMapping(value = { "/t/temp" } )
	public String home( HttpServletRequest request , HttpServletResponse response ) {
		
		JSONObject obj=new JSONObject();
		try {
			
			SysUser user = userRoleService.findUserWithUsernameAndPassword("root", "4c9184f37cff01bcdc32dc486ec36961");
			log.debug("" + user.getUsername());
			
//			UsernamePasswordToken token = new UsernamePasswordToken( "root", "");
//			Subject subject = SecurityUtils.getSubject();
//			subject.login(token);
//			try {
//				userRoleService.test();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
//			Connection c1 = dataSource.getConnection();
//			Connection c2 = dataSource.getConnection();
//			log.debug( c1 +" ||||||||||||||| "+ c2);
//			c1.close();
//			c2.close();
			
			obj.put("result", true);
		} catch (Exception var13) {
			obj.put("result", false);
			log.error("", var13);
		}
		writeJson(obj, response);
		return null;
	}
	
	
	
	@RequestMapping(value = "/login", method = RequestMethod.POST )
	public String login( ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {

		RequestContext requestContext = new RequestContext(request);
		String username = request.getParameter("logname"); 
		String password =  request.getParameter("logpass");
		try {
			
			UsernamePasswordToken token = new UsernamePasswordToken( username , password );
			token.setRememberMe(false);
			Subject subject = SecurityUtils.getSubject();
			
			if( subject.isAuthenticated() ){
				return "redirect:/tlog/tlogs";
			}
			
			subject.login(token);
			
			SysBusinessLog createLoginLog = createLoginLog( username , true);
			SysBusiLogAdditThread.getInstance().addBLog(createLoginLog);
			return "redirect:/tlog/tlogs";
		} catch (Exception var13) {
			
			if( var13 instanceof IncorrectCredentialsException ){
				String message = var13.getMessage() ;
				String msg = requestContext.getMessage( message );
				session.setAttribute("error",  msg );
			}else{
				log.error("", var13);
				session.setAttribute("error", requestContext.getMessage( "Server_error" ) );
			}
			
			SysBusinessLog createLoginLog = createLoginLog( username , false);
			
			SysBusiLogAdditThread.getInstance().addBLog(createLoginLog);
			request.setAttribute("logname", username);
			return "login";
		}
	}
	
	@RequestMapping(value = "/relogin" , method = { RequestMethod.POST , RequestMethod.GET } )
	public String relogin(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj=new JSONObject();
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		try {
			
			UsernamePasswordToken token = new UsernamePasswordToken( userName , password );
			token.setRememberMe(true);
			Subject subject = SecurityUtils.getSubject();
			
			if( subject.isAuthenticated() ){
				return "redirect:/home";
			}
			
			subject.login(token);
			
			Serializable id = subject.getSession().getId();
			
			SysBusinessLog createLoginLog = createLoginLog( userName , true);
			
			SysBusiLogAdditThread.getInstance().addBLog(createLoginLog);
			obj.put("result", true);
			obj.put("sid", id.toString() );
			
		} catch (Exception var13) {
			
			
			obj.put("result", false);
		}
		writeJson(obj, resp);
		return null;
	}
	
	
	@ResponseBody
	@RequestMapping(value = { "/login2" } , method = RequestMethod.POST )
	public String login2(ModelMap modelMap, HttpServletRequest request , HttpSession session) {
		
		RequestContext requestContext = new RequestContext(request);
		
		String JSESSIONID = request.getHeader("JSESSIONID");
		
		String datas = request.getParameter("datas"); 
		JSONObject parseObject = JSONObject.parseObject(datas);
		String username = parseObject.getString("logname"); 
		String password =  parseObject.getString("logpass");
		
//		String username = request.getParameter("logname"); 
//		String password =  request.getParameter("logpass");
		
		try {
			
			UsernamePasswordToken token = new UsernamePasswordToken( username , password );
			token.setRememberMe(false);
			Subject subject = SecurityUtils.getSubject();
			
			if( subject.isAuthenticated() ){
				return createRes(subject);
			}
			
			subject.login(token);
			
			SysBusinessLog createLoginLog = createLoginLog( username , true);
			SysBusiLogAdditThread.getInstance().addBLog(createLoginLog);
			return createRes(subject);
		} catch (Exception var13) {
			
			if( var13 instanceof IncorrectCredentialsException ){
				String message = var13.getMessage() ;
				String msg = requestContext.getMessage( message );
				session.setAttribute("error",  msg );
			}else{
				log.error("", var13);
				session.setAttribute("error", requestContext.getMessage( "Server_error" ) );
			}
			SysBusinessLog createLoginLog = createLoginLog( username , false);
			SysBusiLogAdditThread.getInstance().addBLog(createLoginLog);
			request.setAttribute("logname", username);
			return "{res:false}";
		}
	}
	
	
	private String createRes(Subject subject) {
		JSONObject ret = new JSONObject();
		ret.put("res", true);
		ret.put("sid", subject.getSession().getId() );
		return ret.toString();
	}

	
	@ResponseBody
	@RequestMapping(value = { "/keepalive2" } , method = RequestMethod.POST )
	public String keepalive(ModelMap modelMap, HttpServletRequest request , HttpSession session) {
		
		String JSESSIONID = request.getHeader("JSESSIONID");
		
		String datas = request.getParameter("datas"); 
		JSONObject parseObject = JSONObject.parseObject(datas);
		String sid = parseObject.getString("sid"); 
		
		Subject subject = SecurityUtils.getSubject();
		String id = subject.getSession().getId().toString();
		
		log.debug(sid +" == " +  id);
		
		
		return "{res:true}";
	}
	


	/**
	 * 在通过shiro的 subject.logout() 进行登出loginout之后 通过spring的return
	 * "redirect:/ "; 方式跳转到其他的controller中，根据逻辑
	 * 会在跳转之前讲回话的session删除，但是在跳转的过程中会将之前的session传递到后续的过滤器中
	 * ，从而在shiro中获取不到对应的session；
	 * 跳转jsp页面也会出现相同的问题。因为jsp页面会产生获取session。
	 * 
	 * 解决办法，分步操作，通过ajax请求进行登出操作，然后通过js进行页面跳转。
	 */
	@RequestMapping(value = "/logOut", method = { RequestMethod.POST , RequestMethod.GET } )
	public String logOut(  HttpServletRequest request , HttpServletResponse resp ){
		JSONObject retObj = new JSONObject();
		try {
			Subject subject = SecurityUtils.getSubject();
			if( subject.isAuthenticated() ){
				String userName = subject.getPrincipal().toString();
				subject.logout();
				SysBusinessLog createLogoutLog = createLogoutLog(userName);
				SysBusiLogAdditThread.getInstance().addBLog(createLogoutLog);
				retObj.put("result", true);
			}else{
				retObj.put("result", true);
			}
		} catch (Exception e) {
			retObj.put("result", false);
			log.error("", e);
		}
		writeJson(retObj, resp);
		
		return null;
	}
	
	@RequestMapping(value = "/helpAndSupport", method = { RequestMethod.POST , RequestMethod.GET } )
	public String helpAndSupport(  HttpServletRequest request  ){
		
		try {
			
		} catch (Exception e) {
			log.error("", e);
		}
		
		return "/helpAndSupport";
	}
	
	@RequestMapping(value = "/blankPage", method = { RequestMethod.POST , RequestMethod.GET } )
	public String blankPage(  HttpServletRequest request  ){
		
		try {
			
		} catch (Exception e) {
			log.error("", e);
		}
		
		return "common/blankPage";
	}
	
	
	@RequestMapping(value = "language" , method = { RequestMethod.POST , RequestMethod.GET } )
	public String language( HttpServletRequest  req , HttpServletResponse resp){
		
		try {
			String parameter = req.getParameter("language");
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			if( "zh".equals(parameter)  ){
				session.setAttribute(ServerConstants.SESSION_KEY_LANGUAGE_STR , "zh");
				req.getSession().setAttribute(
						SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, 
						ServerParams.ZH_CN);
			}else if( "en".equals(parameter) ){
				session.setAttribute(ServerConstants.SESSION_KEY_LANGUAGE_STR , "en");
				req.getSession().setAttribute(
						SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, 
						ServerParams.EN_US);
			}
			JSONObject obj = new JSONObject();
			obj.put("result", true);
			writeJson(obj, resp);
		} catch (Exception e) {
			log.error("" , e);
		}
		
		
		return null;
	}
	
	
	private static SysBusinessLog createLoginLog( String userName, boolean isSuccess ){
		
		SysBusinessLog login = new SysBusinessLog();
		
		login.setOperTimeStamp(System.currentTimeMillis());
		login.setOperKey("1");
		login.setOperDesc("Login");
		login.setOperUserName(userName);
		login.setOperResult(isSuccess+"");
		
		return login;
	}
	
	private static SysBusinessLog createLogoutLog( String userName  ){
		
		SysBusinessLog logout = new SysBusinessLog();
		
		logout.setOperTimeStamp(System.currentTimeMillis());
		logout.setOperKey("1");
		logout.setOperDesc("Logout");
		logout.setOperUserName(userName);
		logout.setOperResult("true");
		
		return logout;
	}
	

	@RequestMapping(value = "/changePassword" , method = { RequestMethod.POST , RequestMethod.GET } )
	public String changePassword(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			SysUser user=new SysUser();
			String username = req.getParameter("username");
			String oldPassword = req.getParameter("oldPassword");
			String newPassword = req.getParameter("newPassword");
			user.setUsername(username);
			boolean changePassword=userRoleService.updExpiredPassword(user, oldPassword, newPassword);
			obj.put("result", changePassword);
		}catch (Exception e) {	
			log.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	

}
